package com.zip4j;

import cn.hutool.core.collection.CollectionUtil;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.AesKeyStrength;
import net.lingala.zip4j.model.enums.EncryptionMethod;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jlm
 * @date 2023/07/19 18:21
 */

public class ZipFileUntil {

    public static final String ZIP_PS = "testS.137474as";

    public static boolean zipFile(String tar, String sourcePath) {
        return zipFile(tar, null, sourcePath,null,new String[0]);
    }

    public static boolean zipFile(String tar, char[] password, List<String> filePathList) {

        return zipFile(tar,password,null, filePathList,new String[0]);
    }
    public static boolean zipFile(String tar,char[] password,String[] dirPathList){
        return zipFile(tar,password,null,null,dirPathList);
    }

    public static boolean zipFile(String tar, char[] password, String sourcePath) {
        return zipFile(tar,password,sourcePath, null,new String[0]);
    }
    public static boolean zipFile(String tar, char[] password, String sourcePath,List<String> fileList,String[] dirPathList) {
        if (!new File(tar).getParentFile().exists()) {
            boolean mkdirs = new File(tar).getParentFile().mkdirs();
            System.out.println("创建压缩目录"+ mkdirs);
        }
        //压缩文件
        try (ZipFile zipFile = new ZipFile(tar)) {
            ZipParameters zipParameters = new ZipParameters();
            if (password != null) {
                zipFile.setPassword(password);
                zipParameters.setEncryptFiles(true);
                zipParameters.setEncryptionMethod(EncryptionMethod.AES);
                // Below line is optional. AES 256 is used by default.
                // You can override it to use AES 128. AES 192 is supported only for extracting.
                zipParameters.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_256);
            }
            if(sourcePath!=null){
                zipFile.addFolder(new File(sourcePath), zipParameters);
            }
            if(dirPathList.length!=0){
                for (String source : dirPathList) {
                    zipFile.addFolder(new File(source), zipParameters);
                }
            }

            if(CollectionUtil.isNotEmpty(fileList)){
                List<File> files = new ArrayList<>();
                for (String file : fileList) {
                    files.add(new File(file));
                }
                zipFile.addFiles(files, zipParameters);
            }

        } catch (ZipException e) {
            System.out.println("文件压缩失败，message:"+ e.getMessage());
            return false;
        } catch (IOException e) {
            System.out.println("文件压缩失败，io exception message:"+ e.getMessage());
            return false;
        }
        return true;
    }

}
